package crowx.android.AndCellTrack.BtsDB;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import edu.wlu.cs.levy.CG.KDTree;
import edu.wlu.cs.levy.CG.KeyDuplicateException;
import edu.wlu.cs.levy.CG.KeySizeException;

public class BtsDB {
	private KDTree<BtsInfo> kdTree = new KDTree<BtsInfo>(2);
	
	public void add(BtsInfo btsInfo) {
		try {
			kdTree.insert(btsInfo.getKey(), btsInfo);
		} catch (KeySizeException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		} catch (KeyDuplicateException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		//kdTree.ne
	}
	
	public void loadFromCLFFile(InputStream clfFile) {
		BufferedReader in = new BufferedReader(new InputStreamReader(clfFile));
		String line = null;
		try {
			line = in.readLine();
		} catch (IOException e) {
			android.util.Log.e("AndCellTrack", "readLine error", e);
		}
		while(line != null) {
			try {
				BtsInfo tmp = new BtsInfo(line);
				add(tmp);
			}
			catch(IllegalArgumentException e) {
				android.util.Log.w("AndCellTrack", "new CLFRecord error");
			}
			try {
				line = in.readLine();
			} catch (IOException e) {
				android.util.Log.e("AndCellTrack", "readLine error", e);
				break;
			}
		}
	}
	
	public List<BtsInfo> getNearest(double[] key, int n) {
		try {
			return kdTree.nearest(key, n);
		} catch (KeySizeException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		return null;
	}
}
